package logic

import (
	"context"
	"encoding/json"
	"goods-ctrl/cache"
	"goods-ctrl/model"
	"time"

	"goods-ctrl/goodsrpc/goodsrpc"
	"goods-ctrl/goodsrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsListLogic) GoodsList(in *goodsrpc.GoodsListRequest) (*goodsrpc.GoodsListResponse, error) {
	// todo: add your logic here and delete this line

	var goods []model.Shops

	data, _ := cache.Rdb.Get(l.ctx, "GoodsList").Result()
	if data == "" {
		model.DB.Debug().Table("goods").
			Select("goods.*,brands.name as brand_name,classes.name as class_name").
			Joins("left join brands on brands.id = goods_brand.id").
			Joins("left join classes on classes.id = goods_class.id").
			Scan(&goods)

		mashal, _ := json.Marshal(data)
		cache.Rdb.Set(l.ctx, "GoodsList", mashal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(data), &goods)
	}

	var goodsList []*goodsrpc.GoodsList
	for _, m := range goods {

		list := goodsrpc.GoodsList{
			Name:      m.Name,
			Age:       m.Age,
			BrandName: m.BrandName,
			ClassName: m.ClassName,
		}
		goodsList = append(goodsList, &list)
	}
	return &goodsrpc.GoodsListResponse{
		List: goodsList,
	}, nil
}
